package com.dabai.opdoubleopen.ui;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;

import com.afollestad.materialdialogs.MaterialDialog;
import com.dabai.opdoubleopen.BuildConfig;
import com.dabai.opdoubleopen.R;
import com.dabai.opdoubleopen.shizuku.Shell;
import com.dabai.opdoubleopen.shizuku.ShizukuShell;
import com.dabai.opdoubleopen.utils.DabaiUtils;
import com.dabai.opdoubleopen.utils.ShellUtils;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SettingsActivity extends AppCompatActivity {

    public static String TAG = "LogTag";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings_activity);
        if (savedInstanceState == null) {
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.settings, new SettingsFragment())
                    .commit();
        }
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle presses on the action bar items
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    public static class SettingsFragment extends PreferenceFragmentCompat {
        private Context context;

        @Override
        public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
            setPreferencesFromResource(R.xml.root_preferences, rootKey);

            context = getContext();
            //version init  版本号初始化
            final Preference ver = getPreferenceManager().findPreference("key_version");
            assert ver != null;
            ver.setSummary(BuildConfig.VERSION_NAME + "(" + BuildConfig.VERSION_CODE+")");
            refId();
        }

        @Override
        public boolean onPreferenceTreeClick(Preference preference) {

            switch (preference.getKey()) {
                case "key_user":
                    //多用户列表
                    try {
                        manyUsersList();
                    } catch (Exception e) {
                        DabaiUtils.showDialog(context,context.getResources().getString(R.string.list_users_access_to_fail));
                    }
                    break;
                case "key_community":
                    DabaiUtils.openLink(context, "https://support.qq.com/product/159271");
                    break;
                case "key_version":
                    DabaiUtils.toMyAppInfo(context);
                    break;
                case "key_update":
                    DabaiUtils.openLink(context,"https://www.coolapk.com/apk/com.dabai.opdoubleopen");
                    break;
            }
            return super.onPreferenceTreeClick(preference);
        }

        /**
         * 多用户列表 与 选择用户
         */
        private void manyUsersList() throws Exception{
            SharedPreferences sp = context.getSharedPreferences(context.getPackageName() + "_preferences", 0);
            String mode = sp.getString("mode", "null");

            String shellUserListStr = "pm list users";
            String usersStr = "";

            if (mode.equals("null") || mode.equals("root")) {
                ShellUtils.CommandResult commandResult = ShellUtils.execCommand(shellUserListStr, true, true);
                if (commandResult.result == 0) {
                    usersStr = commandResult.successMsg;
                } else {
                    usersStr = commandResult.errorMsg;
                }
            } else if (mode.equals("shizuku")) {
                Shell.Result commandResult = ShizukuShell.getInstance().exec(new Shell.Command(shellUserListStr));
                if (commandResult.exitCode == 0) {
                    usersStr = commandResult.out;
                } else {
                    usersStr = commandResult.err;
                }
            }


            //解析用户列表
            ArrayList<String> userList = new ArrayList<>();

            if (usersStr.toLowerCase().contains("UserInfo".toLowerCase())){
                //检测到用户 字符串

                String patternStr = "\\{.*?\\}";
                Pattern pattern = Pattern.compile(patternStr);
                Matcher matcher = pattern.matcher(usersStr);
                while (matcher.find()) {
                    userList.add(matcher.group().replace("{","").replace("}",""));
                }

                new MaterialDialog.Builder(context)
                        .title(getString(R.string.select_target_user))
                        .positiveText(R.string.deselect)
                        .neutralText(getString(R.string.restore_default_value))
                        .items(userList)
                        .itemsCallback((dialog, view, which, text) -> {

                            String id = text.toString().split(":")[0];
                            Log.d(TAG, "id: "+id);
                            if (id.length() < 5 && id.length()>0 && DabaiUtils.isNumeric(id)){
                                DabaiUtils.setSharedPreferencesString(context,"user",id);
                                refId();

                            }else {
                                DabaiUtils.showDialog(context,context.getResources().getString(R.string.choose_to_fail));
                            }

                        })
                        .onNeutral((dialog, which) -> {
                            DabaiUtils.setSharedPreferencesString(context,"user","999");
                            refId();

                        })
                        .show();

            }else {
                //检测失败
                DabaiUtils.showDialog(context,context.getString(R.string.list_users_access_to_fail));
            }
        }

        private void refId() {
            final Preference user = getPreferenceManager().findPreference("key_user");
            assert user != null;
            user.setSummary(getString(R.string.cou_user)+ android.os.Process.myUserHandle().describeContents() + " - "+getString(R.string.tag_user) + DabaiUtils.getSharedPreferencesString(context, "user", "999"));
        }
    }


}